package com.juvepoland.jpdroid.activities;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.juvepoland.jpdroid.R;
import com.juvepoland.jpdroid.adapters.LazyNewsAdapter;
import com.juvepoland.jpdroid.application.JPdroidApplication;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.media.ExifInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

/**
 * EN:
 * <br/>
 * Super class that represents all of activities in application.
 * Contains info about fonts and some menu common behavior.
 * Contains AsyncActionClass, which could be run in any child-class for
 * presenting loading data.
 * <br/>
 * PL:
 * <br/>
 * Klasa rodzic, po której dziedziczą wszystkie aktywności w aplikacji.
 * Zawiera informacje o czcionce, wspólnej logiki działania menu.
 * Zawiera AsyncActionClass, która jest odpowiedzialna za przedstawienie 
 * animacji wczytywania/przetwarzania danych
 * @author Andrzej
 *
 */
public abstract class BasicActivity extends Activity {
	
	protected ProgressDialog pDialog;
	protected InputStream rawResource;
	protected Properties properties;
	protected Typeface basicFontTypeFace;
	protected Typeface basicItalicFontTypeFace;
	protected static final String MY_PREFERENCES = MyPreferencesActivity.MY_PREFERENCES;
	protected SharedPreferences sharedPreferences;
	protected SharedPreferences.Editor sharedPreferenceEditor;


	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		pDialog = new ProgressDialog(BasicActivity.this);
		try {
			rawResource = this.getResources().openRawResource(R.raw.jpdroid);
			properties = new Properties();
			properties.load(rawResource);			
		} catch (IOException e) {
			Toast.makeText(getApplicationContext(), "Błąd ładowania pliku properties! " + e.getMessage(),
					Toast.LENGTH_LONG).show();
			finish();
		}
		sharedPreferences = getSharedPreferences(MY_PREFERENCES, Activity.MODE_PRIVATE);
		basicFontTypeFace = Typeface.createFromAsset(getAssets(), getBasicFontName());
		basicItalicFontTypeFace = Typeface.createFromAsset(getAssets(), getBasicItalicFontName());
		sharedPreferenceEditor = sharedPreferences.edit();
	}

	/**
	 * EN:
	 * <br/>
	 * Hide/Show Login/Logout action wheter user is authenticated or not
	 * <br/>
	 * PL:
	 * <br/>
	 * Ukrywa bądź pokazuje standardowe akcje Zaloguj/Wyloguj, 
	 * w zależności od tego, czy użytkownik jest zalowogany, czy też nie.
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		JPdroidApplication app = (JPdroidApplication)getApplicationContext();
		MenuItem loginMenuItem = menu.findItem(R.id.login_bookmark);
		MenuItem logoutMenuItem = menu.findItem(R.id.logout_bookmark);
		if(app.isUserLogged()){
			if(loginMenuItem!=null){
				loginMenuItem.setVisible(false);
			}
			if(logoutMenuItem!=null){
				logoutMenuItem.setVisible(true);
			}
		}
		else{
			if(loginMenuItem!=null){
				loginMenuItem.setVisible(true);
			}
			if(logoutMenuItem!=null){
				logoutMenuItem.setVisible(false);
			}
		}
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.login_bookmark){
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			return true;
		}
		else if(item.getItemId() == R.id.logout_bookmark){
			AlertDialog alertDialog = new AlertDialog.Builder(this).create();
			alertDialog.setTitle("Wyloguj");
			alertDialog.setMessage("Na pewno wylogować?");
			alertDialog.setButton("Tak", new DialogInterface.OnClickListener() {
				   public void onClick(DialogInterface dialog, int which) {
					   JPdroidApplication app = (JPdroidApplication)getApplicationContext();
						app.setLoggedUser(null);
						sharedPreferenceEditor.remove("username");
						sharedPreferenceEditor.remove("password");
						sharedPreferenceEditor.commit();
						Toast.makeText(getApplicationContext(), "Wylogowano pomyślnie.", Toast.LENGTH_SHORT).show();
						doAfterLogout();
				   }
				});
			alertDialog.show();
			return true;
		}
		else return super.onOptionsItemSelected(item);
	}
	protected void doAfterLogout(){	//TODO Przemienić na abstract
		
	}
		
	

	/**
	 * EN:
	 * <br/>
	 * Makes a process doInBackground() of AsyncTask class while loading an activity. May be left empty.
	 * <br/>
	 * PL:
	 * <br/>
	 * Wykonuje proces doInBackround() z klasy AsyncTask podczas standardowego ładowania aktywności.
	 * Można zostawić pustą.
	 * @throws Exception
	 */
	protected abstract void doInBackgroundAsyncProcess() throws Exception;
	
	protected Intent getIntentToReturnAfterLogout(){	//TODO przemienić na abstract
		return null;
	}
	
	protected class AsyncActionClass extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... arg0) {
			runOnUiThread(new Runnable() {
                public void run() {
                	try {
                		doInBackgroundAsyncProcess();
					} catch (Exception e) {
						Toast.makeText(getApplicationContext(), "Błąd! " + e.getMessage(),
								Toast.LENGTH_LONG).show();
						e.printStackTrace();
					}
                }
			});
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			pDialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
            
            pDialog.setMessage("Przetwarzanie danych, proszę czekać...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
		}
		
	}

	private String getBasicFontName(){
		String font = sharedPreferences.getString(MyPreferencesActivity.PREFERENCE_DEFAULT_FONT_NAME, null);
		return font == null ? properties.getProperty("basicNormalFont") : font;
	}
	private String getBasicItalicFontName(){
		return properties.getProperty("basicItalicFont");		
	}
	
	public void getActionToReturnAfterBackButton(){
		finish();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			getActionToReturnAfterBackButton();
			return true;
		}
		else{
			return super.onKeyDown(keyCode, event);
		}
		
	}
	
	
}
